// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    chat: [],
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    userInfo: {},
    inputText: ''
  },

  onLoad() {
    
  },
  // 创建连接。
  // type: 自定义对象1是加入聊天，2是聊天信息，3是退出聊天。
  // direction: 0左，1右
  onConnect:function(){
    let that=this
    var data = []
    wx.connectSocket({
      url: 'ws://192.168.43.172:9001',
      // url: 'ws://192.168.43.172:9001',
      success:function(){
        wx.onSocketMessage((result) => {
        console.log("服务器返回的数据",result)
        let res = result.data.split(":")
        
        // console.log('切割后',res)

        //新用户加入处理方式，数组必须大于二
        if(res.length>1 && res.length < 3){
          console.log('切割后',res)
          //新加入聊天
          if(res[1].replace(/^\s+|\s+$/g,"") === "加入聊天"){
            data.push({
              type: 1,
              user: res[0].split("新")[1].replace(/^\s+|\s+$/g,"")
            })
          }
          //存聊天内容
          if(res[1].replace(/^\s+|\s+$/g,"") != "退出群聊" && res[1].replace(/^\s+|\s+$/g,"")!=null){
            for(let i = 0;i<data.length;i++){
              // console.log(res[0],data[i].user)
              if(res[0] == data[i].user){
                //本机发的消息
                if(data[i].nickName == that.data.userInfo.nickName && data[i].avatarUrl == that.data.userInfo.avatarUrl){
                  data.push({
                    type: 2,
                    direction: 1,
                    user: res[0],
                    nickName: data[i].nickName,
                    avatarUrl: data[i].avatarUrl,
                    content: res[1]
                  })
                  break;
                }else{
                  data.push({
                    type: 2,
                    direction: 0,
                    user: res[0],
                    nickName: data[i].nickName,
                    avatarUrl: data[i].avatarUrl,
                    content: res[1]
                  })
                  break;
                }
              }
            }
          }
          //退出群聊
          if(res[1].replace(/^\s+|\s+$/g,"") == "退出群聊"){
            for(let i = 0;i<data.length;i++){
              if(res[0].replace(/^\s+|\s+$/g,"") == data[i].user){
                data.push({
                  type: 3,
                  user: res[0].replace(/^\s+|\s+$/g,""),
                  nickName: data[i].nickName
                })
                break;
              }
            }
          }
        }
        //存用户信息
        if(res.length>3){
          console.log('result------------------',result.data)
          // 是否存在用户信息，默认false不存在
          let flag = true;
            for(let i = 0;i<data.length;i++){
              if(res[0].replace(/^\s+|\s+$/g,"") == data[i].user.replace(/^\s+|\s+$/g,"")){
                // 用户初始信息
                let userInfo = JSON.parse(result.data.split(res[0])[1].slice(2))
                data[i].nickName=userInfo.nickName
                data[i].avatarUrl=userInfo.avatarUrl
                flag = true
              }else{
                flag = false
              }
            }
            if(!flag){
              let userInfo = JSON.parse(result.data.split(res[0])[1].slice(2))
              data.push({
                user: res[0].replace(/^\s+|\s+$/g,""),
                nickName: userInfo.nickName,
                avatarUrl: userInfo.avatarUrl
              })
            }

        }
        console.log('我封装的数据',data)
        that.setData({
          chat: data
        })
        })
        setTimeout(that.sendUser,100)
      }
    })
  },
  //发送用户信息给服务器，服务器返回给我
  sendUser:function () {
    // var jsonp
    let user={}
    user.nickName=this.data.userInfo.nickName
    user.avatarUrl = this.data.userInfo.avatarUrl
    user=JSON.stringify(user)
    wx.sendSocketMessage({
      data: user,
    })
  },
  // 得到我输入的内容
  getContent:function(e){
    this.setData({
      inputText: e.detail.value
    })
  },
  // 发送我输入的内容
  onsend:function(){
    let that=this
    let user={}
    user.nickName=that.data.userInfo.nickName
    user.avatarUrl = that.data.userInfo.avatarUrl
    user=JSON.stringify(user)
    wx.sendSocketMessage({
      data: user,
    })
    wx.sendSocketMessage({
      data: this.data.inputText,
      success:function(res){
      }
    })
   
  },


  // 关闭连接
  onClose:function(){
    wx.closeSocket({
    })
  },
  getUserInfo() {
    wx.getSetting({
      success (res){
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function(res) {
              console.log(res.userInfo)
            }
          })
        }
      }
    })
  },
  bindGetUserInfo (e) {
    console.log(e.detail.userInfo)
    this.setData({
      userInfo: e.detail.userInfo
    })
  }
})
